//
//  ZDPhotoBrowserViewController.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/11/7.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

let ZDCollectionViewPadding: CGFloat = 10

class ZDPhotoBrowserViewController: UIViewController {
    
    let reuseIdentifier = "ZDPhotoBrowserCell"
    
    var index: Int = 0
    
    var models = [ZDPhotoBrowserModel]()
    
    
    init(index: Int, models: [ZDPhotoBrowserModel]) {
    
        super.init(nibName: nil, bundle: nil)
        
        self.index = index
        self.models = models
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //控制器view的背景颜色设置成透明
        view.backgroundColor = UIColor.clearColor()

        prepareUI()
        
        //注册cell
        photoBrowserCollectionView.registerClass(ZDPhotoBrowserCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    
    override func viewWillAppear(animated: Bool) {
        
        super.viewWillAppear(animated)
        
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        
        //滚动到指定页
        photoBrowserCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
//        photoBrowserCollectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
    }

    
    //MARK: - 准备UI
    private func prepareUI() {
    
        //添加子控件
        view.addSubview(bkgView)  //背景view应该添加到最下面 否则会遮住collectionView
        view.addSubview(photoBrowserCollectionView)
        view.addSubview(indicatorLabel)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        //为按钮添加事件
        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBtn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        
//        photoBrowserCollectionView.translatesAutoresizingMaskIntoConstraints = false
        indicatorLabel.translatesAutoresizingMaskIntoConstraints = false
        closeBtn.translatesAutoresizingMaskIntoConstraints = false
        saveBtn.translatesAutoresizingMaskIntoConstraints = false
        
        bkgView.frame = view.bounds
        
        let views = [
        
            "pbcv": photoBrowserCollectionView,
            "il": indicatorLabel,
            "cb": closeBtn,
            "sb": saveBtn
        ]
        
        //添加约束
        //photoBrowserCollectionView
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[pbcv]-(-10)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[pbcv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        //改成frame也可以 使用约束也行
        photoBrowserCollectionView.frame = CGRectMake(0, 0, UIScreen.width + ZDCollectionViewPadding, UIScreen.height)
        
        //indicatorLabel
        view.addConstraint(NSLayoutConstraint(item: indicatorLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: indicatorLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 20))
        
        //closeBtn 垂直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        //saveBtn 垂直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        //水平方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[cb(75)]-(>=0)-[sb(75)]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
    }
    
    
    //MARK: - 按钮点击事件
    @objc private func close() {
    
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 保存图片
    @objc private func save() {
    
        //当前显示那个cell
        let indexPath = photoBrowserCollectionView.indexPathsForVisibleItems().first!
        
        //根据indexPath取出cell
        let cell = photoBrowserCollectionView.cellForItemAtIndexPath(indexPath) as! ZDPhotoBrowserCell
        
        //取出cell中展示的图片
        if let image = cell.imageView.image {
        
            //保存图片
            //- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        }
    }
    
    
    ///保存图片回调方法
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?)
    {
        if error != nil {
        
            SVProgressHUD.showErrorWithStatus("保存失败", maskType: SVProgressHUDMaskType.Black)
            
            return
        }
        
        SVProgressHUD.showSuccessWithStatus("保存成功", maskType: SVProgressHUDMaskType.Black)
    }
    
   
    //MARK: - 懒加载
    ///懒加载collectionView
    lazy var photoBrowserCollectionView: ZDPhotoBrowserCollectionView = {
    
        let cv = ZDPhotoBrowserCollectionView()
        
        //设置collectionView的背景颜色为透明
        cv.backgroundColor = UIColor.clearColor()
        
        //设置数据源
        cv.dataSource = self
        //设置代理
        cv.delegate = self
        
        return cv
    }()
    
    ///懒加载indicatorLabel
    private lazy var indicatorLabel: UILabel = {
    
        let label = UILabel(fontSize: 18, color: UIColor.whiteColor())
        
        label.text = "\(self.index+1) / \(self.models.count)"
    
        return label
    }()
    
    ///懒加载关闭按钮
    private lazy var closeBtn: UIButton = UIButton(title: "关闭")
    
    ///懒加载保存按钮
    private lazy var saveBtn: UIButton = UIButton(title: "保存")
    
    ///懒加载背景view
    private lazy var bkgView: UIView = {
    
        let view = UIView()
        
        view.backgroundColor = UIColor.blackColor()
        
        return view
    }()
}



extension ZDPhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return models.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ZDPhotoBrowserCell
        
        //指定代理
        if (cell.delegate == nil) {
        
            cell.delegate = self
        }
        
        cell.backgroundColor = UIColor.clearColor()
        
        cell.model = models[indexPath.item]
        
        return cell
    }
    
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        let index = photoBrowserCollectionView.indexPathsForVisibleItems().first!.item
        
        indicatorLabel.text = "\(index+1) / \(self.models.count)"
    }
}


//MARK: - 控制器做cell的代理
extension ZDPhotoBrowserViewController: ZDPhotoBrowserCellDelegate {

    //返回控制器的view
    func viewForTransparent() -> UIView {
        
        return bkgView
    }
    
    func scaleDismiss() {
        
        //关闭控制器 取消动画 ———— 如果动画打开，由于我们实现了转场动画，会执行转场动画
        dismissViewControllerAnimated(false, completion: nil)
    }
}


//MARK: - 转场动画
extension ZDPhotoBrowserViewController: UIViewControllerTransitioningDelegate {

    ///modal动画
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        return ZDPhotoBrowserModalAnimation()
    }
    
    ///dismiss动画
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        return ZDPhotoBrowserDismissAnimation()
    }
}


extension ZDPhotoBrowserViewController {

    //提供转场动画的过渡视图  需要知道显示的图片 还要知道显示的imageView的frame
    
    ///创建modal过渡视图
    func modalTempImageView() -> UIImageView {
    
        //创建缩略视图 ———— 微博配图视图
        let thumbImageView = models[index].imageView!
        
        //创建过渡视图
        let tempImageView = UIImageView(image: thumbImageView.image)
        
        //设置参数
        tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
        tempImageView.clipsToBounds = true
        
        //设置frame ———— 需要转换坐标系
        tempImageView.frame = thumbImageView.superview!.convertRect(thumbImageView.frame, toCoordinateSpace: view)
        
        return tempImageView
    }
    
    ///返回modal动画时放大的frame
    func modalTargetFrame() -> CGRect {
    
        //创建缩略视图 ———— 微博配图视图
        let thumbImageView = models[index].imageView!
        
//        let image = thumbImageView.image!
        
        guard let image = thumbImageView.image else {
        
            return CGRectZero
        }
        
        //获取放大后的size
        let newSize = image.displaySize()
        
        if newSize.height < UIScreen.height {
        
            return CGRect(x: 0, y: (UIScreen.height-newSize.height)*0.5, width: newSize.width, height: newSize.height)
        }
        else {
        
            return CGRect(x: 0, y: 0, width: newSize.width, height: UIScreen.height)
        }
    }
    
    
    ///获取dismiss过渡视图
    func dismissTempImageView() -> UIImageView {
    
        //获取正在显示的图片
        let indexPath = photoBrowserCollectionView.indexPathsForVisibleItems().first!
        
        let cell = photoBrowserCollectionView.cellForItemAtIndexPath(indexPath) as! ZDPhotoBrowserCell
        
        let image = cell.imageView.image
        
        //创建过渡视图
        let tempImageView = UIImageView(image: image)
        
        //设置参数
        tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
        tempImageView.clipsToBounds = true
        
        //设置frame ———— 坐标系转换
        tempImageView.frame = cell.imageView.superview!.convertRect(cell.imageView.frame, toCoordinateSpace: view)
        
        return tempImageView
    }
    
    ///返回dismiss动画时缩小的frame
    func dismissTargetFrame() -> CGRect {
        
        //获取正在显示的图片
        let indexPath = photoBrowserCollectionView.indexPathsForVisibleItems().first!
    
        //获取对应缩略图
        let thumbImageView = models[indexPath.item].imageView!
        
        //坐标系转换
        let rect = thumbImageView.superview!.convertRect(thumbImageView.frame, toCoordinateSpace: view)
        
        return rect
    }
}
